//
//  TQAFNetworkDownload.m
//  TiaoQu
//
//  Created by shuihulu on 14/12/26.
//  Copyright (c) 2014年 wsp. All rights reserved.
//
#define SECRET_KEY @"bGJv9Tul6CJOFw08"

#import "TQAFNetworkDownload.h"
#import <AFNetworking/AFNetworking.h>
#import "NSString+Ext.h"

@implementation TQAFNetworkDownload



#pragma mark    - - -单例- - -

/**
 设置单例
 */
static id instance;

#pragma mark    -   -   - 设计单例 -    -   -
+ (instancetype)shareTQAFNetwork
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!instance) {
            instance = [[self alloc] init];
        }
    });
    
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance == nil) {
            instance = [super allocWithZone:zone];
        }
    });
    
    return instance;
}

#pragma mark -download
/**
 *  userID 用户编号 -1未注册
 *  stime 时间戳，格式yyyyMMddHHmmss。如20130419151210
	encryptstr userID- stime-KEY 以“-”分隔三个userID、stime、KEY，MD5加密，密文为小写
 mobile 手机号码
	imei 设备编号
 platform 终端
 versionnumber 版本号
 installedSource 装机来源
 NetType 网络状态
 *
 */
+ (void) downloadUserID:(NSString *)useridstr
				reqType:(NSString *)reqType//域名
			  reqMethod:(NSString *)reqMethod
		andOtherKeyDict:(NSDictionary *)keyDicts
		successDownload:(NetDownLoadSuccessIdBlock)successDownload
		failureDownload:(NetDownLoadFailureIdBlock)failureDownload{
    NSString *xlapi = BaseURL;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isTestUrl"]isEqualToString:@"yes"]) {
        xlapi = @"http://test.xinliao.xiuquapp.com";
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",xlapi,reqMethod];
    //必须的参数
    
    NSMutableDictionary *parametersN = [[NSMutableDictionary alloc] init];
    [parametersN setObject:[XLAccountManager shareInstance].model.Id forKey:@"userId"];
    //数据下载
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", @"text/json",nil];
    [manager.requestSerializer setValue:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] forHTTPHeaderField:@"version"];
    [manager.requestSerializer setValue:QudaoName forHTTPHeaderField:@"qudao"];
    [manager.requestSerializer setValue:[NSString iPhoneName] forHTTPHeaderField:@"phoneType"];
    [manager.requestSerializer setValue:[[UIDevice currentDevice] systemVersion] ?:@"" forHTTPHeaderField:@"osVersion"];
    [manager.requestSerializer setValue:[UserDefaults objectForKey:UserID] forHTTPHeaderField:@"userId"];
    [manager.requestSerializer setValue:[UserDefaults objectForKey:UserToken] forHTTPHeaderField:@"token"];
    [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"appId"];
    manager.requestSerializer.timeoutInterval = 26.0f;//时间（可以不设置）
    	NSLog(@"%@",parametersN);
    [manager GET:url parameters:parametersN progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            NSDictionary *restultDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            successDownload(restultDict);
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@", error);
        
        failureDownload(error);
    }];

}
+ (void) downloadTaskUserID:(NSString *)useridstr
                reqType:(NSString *)reqType//域名
              reqMethod:(NSString *)reqMethod
        andOtherKeyDict:(NSDictionary *)keyDicts
        successDownload:(NetDownLoadSuccessIdBlock)successDownload
        failureDownload:(NetDownLoadFailureIdBlock)failureDownload{
    NSString *url = [NSString stringWithFormat:@"%@%@",reqType,reqMethod];
    //必须的参数
    NSMutableDictionary *parametersN = [[NSMutableDictionary alloc] init];
    [parametersN setObject:[XLAccountManager shareInstance].model.Id forKey:@"userId"];
    //数据下载
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", @"text/json",nil];
    
    manager.requestSerializer.timeoutInterval = 26.0f;//时间（可以不设置）
    NSLog(@"%@",parametersN);
    [manager GET:url parameters:parametersN progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            NSDictionary *restultDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            successDownload(restultDict);
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@", error);
        
        failureDownload(error);
    }];
}
//json请求
- (void)TQAFNetworkHttpRequestJsonStyle:(NSString *)GetOrPost Url:(NSString *)url parameter:(NSDictionary *)paramater success:(void (^)(id))success failt:(void (^)(NSError *))failt {
    
    NSString *xlapi = BaseURL;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isTestUrl"]isEqualToString:@"yes"]) {
        xlapi = @"http://test.xinliao.xiuquapp.com";
    }
    NSString *xlUrl = [NSString stringWithFormat:@"%@%@",xlapi,url];
    
    NSDictionary *body = paramater;
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:GetOrPost URLString:xlUrl parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setValue:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] forHTTPHeaderField:@"version"];
    [req setValue:QudaoName forHTTPHeaderField:@"qudao"];
    [req setValue:[NSString iPhoneName] forHTTPHeaderField:@"phoneType"];
    [req setValue:[[UIDevice currentDevice] systemVersion] ?:@"" forHTTPHeaderField:@"osVersion"];
    [req setValue:[UserDefaults objectForKey:UserID] forHTTPHeaderField:@"userId"];
    [req setValue:[UserDefaults objectForKey:UserToken] forHTTPHeaderField:@"token"];
    [req setValue:@"1" forHTTPHeaderField:@"appId"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"Reply JSON: %@", responseObject);
            
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                //blah blah
                if (responseObject) {
//                    NSDictionary *restultDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                    success(responseObject);
                    
                }
                
            }
            
        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            failt(error);
            
        }
        
    }] resume];
    
}

@end
